const Router = require('koa-router');
const { pool } = require('../config/db');
const { verifyToken, getTokenFromRequest, authMiddleware } = require('../utils/auth');
const { v4: uuidv4 } = require('uuid');

const router = new Router({
  prefix: '/roles'
});

// 使用自定义的中间件，而不是authMiddleware，因为这里需要自定义错误格式
const roleAuthMiddleware = async (ctx, next) => {
  const token = getTokenFromRequest(ctx);
  
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_REQUIRED',
      errMsg: '未提供token',
      data: null
    };
    return;
  }
  
  const verifyResult = verifyToken(token);
  
  if (!verifyResult.valid) {
    ctx.status = 401;
    ctx.body = {
      errCode: 'TOKEN_INVALID',
      errMsg: verifyResult.message,
      data: null
    };
    return;
  }
  
  // 保存用户ID到ctx.state
  ctx.state.userId = verifyResult.payload.userId;
  
  await next();
};

// 为所有路由添加认证中间件
router.use(roleAuthMiddleware);

/**
 * 确保角色有所有必要的字段
 * @param {object} role 角色信息
 * @param {string} userId 用户ID
 * @returns {object} 完整的角色信息
 */
function ensureRoleFields(role, userId) {
  // 基本字段
  const defaultFields = {
    name: role.name || '',
    description: role.description || '',
    avatar: role.avatar || '/static/avatars/default.png',
    prompt: role.prompt || '',
    greeting: role.greeting || '',
    is_custom: role.isCustom !== undefined ? role.isCustom : true,
    is_default: role.isDefault !== undefined ? role.isDefault : false,
    is_adult: role.isAdult !== undefined ? role.isAdult : false,
    model: role.model || '',
    user_id: userId, // 添加用户ID
    create_time: role.createTime || Date.now(),
    update_time: Date.now()
  };
  
  // 如果是高级角色，添加高级角色特有字段
  if (role.isAdult) {
    return {
      ...defaultFields,
      age: role.age || '',
      gender: role.gender || '',
      occupation: role.occupation || '',
      hobbies: role.hobbies || '',
      appearance: role.appearance || '',
      personality: role.personality || '',
      background: role.background || '',
      scenario: role.scenario || '',
      interaction_priorities: role.interactionPriorities || '',
      attention_points: role.attentionPoints || ''
    };
  }
  
  return defaultFields;
}

/**
 * 获取所有角色（包括系统默认角色和用户自己的角色）
 * POST /roles/getAllRoles
 */
router.post('/getAllRoles', async (ctx) => {
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询条件
    let query;
    let queryParams = [];
    
    // 返回系统默认角色和用户自己的角色
    query = 'SELECT * FROM roles WHERE is_default = ? OR user_id = ?';
    queryParams = [true, userId];
    
    // 执行查询
    const [roles] = await pool.execute(query, queryParams);
    
    // 将下划线命名转换为驼峰命名
    const formattedRoles = roles.map(role => {
      return {
        id: role.id,
        name: role.name,
        description: role.description,
        avatar: role.avatar,
        prompt: role.prompt,
        greeting: role.greeting,
        isCustom: role.is_custom,
        isDefault: role.is_default,
        isAdult: role.is_adult,
        model: role.model,
        userId: role.user_id,
        createTime: role.create_time,
        updateTime: role.update_time,
        age: role.age,
        gender: role.gender,
        occupation: role.occupation,
        hobbies: role.hobbies,
        appearance: role.appearance,
        personality: role.personality,
        background: role.background,
        scenario: role.scenario,
        interactionPriorities: role.interaction_priorities,
        attentionPoints: role.attention_points
      };
    });
    
    ctx.body = {
      errCode: 0,
      errMsg: '获取角色列表成功',
      data: formattedRoles
    };
  } catch (error) {
    console.error('获取角色列表失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_ROLES_FAILED',
      errMsg: '获取角色列表失败：' + error.message,
      data: [] // 发生错误时返回空数组
    };
  }
});

/**
 * 获取高级角色（包括系统默认高级角色和用户自己的高级角色）
 * POST /roles/getAdultRoles
 */
router.post('/getAdultRoles', async (ctx) => {
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询条件
    const query = 'SELECT * FROM roles WHERE is_adult = ? AND (is_default = ? OR user_id = ?)';
    const queryParams = [true, true, userId];
    
    // 执行查询
    const [roles] = await pool.execute(query, queryParams);
    
    // 将下划线命名转换为驼峰命名
    const formattedRoles = roles.map(role => {
      return {
        id: role.id,
        name: role.name,
        description: role.description,
        avatar: role.avatar,
        prompt: role.prompt,
        greeting: role.greeting,
        isCustom: role.is_custom,
        isDefault: role.is_default,
        isAdult: role.is_adult,
        model: role.model,
        userId: role.user_id,
        createTime: role.create_time,
        updateTime: role.update_time,
        age: role.age,
        gender: role.gender,
        occupation: role.occupation,
        hobbies: role.hobbies,
        appearance: role.appearance,
        personality: role.personality,
        background: role.background,
        scenario: role.scenario,
        interactionPriorities: role.interaction_priorities,
        attentionPoints: role.attention_points
      };
    });
    
    ctx.body = {
      errCode: 0,
      errMsg: '获取高级角色列表成功',
      data: formattedRoles
    };
  } catch (error) {
    console.error('获取高级角色列表失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_ADULT_ROLES_FAILED',
      errMsg: '获取高级角色列表失败：' + error.message,
      data: [] // 发生错误时返回空数组
    };
  }
});

/**
 * 获取非高级角色（包括系统默认非高级角色和用户自己的非高级角色）
 * POST /roles/getNonAdultRoles
 */
router.post('/getNonAdultRoles', async (ctx) => {
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询条件
    const query = 'SELECT * FROM roles WHERE is_adult = ? AND (is_default = ? OR user_id = ?)';
    const queryParams = [false, true, userId];
    
    // 执行查询
    const [roles] = await pool.execute(query, queryParams);
    
    // 将下划线命名转换为驼峰命名
    const formattedRoles = roles.map(role => {
      return {
        id: role.id,
        name: role.name,
        description: role.description,
        avatar: role.avatar,
        prompt: role.prompt,
        greeting: role.greeting,
        isCustom: role.is_custom,
        isDefault: role.is_default,
        isAdult: role.is_adult,
        model: role.model,
        userId: role.user_id,
        createTime: role.create_time,
        updateTime: role.update_time,
        age: role.age,
        gender: role.gender,
        occupation: role.occupation,
        hobbies: role.hobbies,
        appearance: role.appearance,
        personality: role.personality,
        background: role.background,
        scenario: role.scenario,
        interactionPriorities: role.interaction_priorities,
        attentionPoints: role.attention_points
      };
    });
    
    ctx.body = {
      errCode: 0,
      errMsg: '获取普通角色列表成功',
      data: formattedRoles
    };
  } catch (error) {
    console.error('获取普通角色列表失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_NON_ADULT_ROLES_FAILED',
      errMsg: '获取普通角色列表失败：' + error.message,
      data: [] // 发生错误时返回空数组
    };
  }
});

/**
 * 根据ID获取角色（只能获取系统默认角色或用户自己的角色）
 * POST /roles/getRoleById
 */
router.post('/getRoleById', async (ctx) => {
  const { id } = ctx.request.body;
  
  // 参数校验
  if (!id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '角色ID不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询角色
    const [roles] = await pool.execute('SELECT * FROM roles WHERE id = ?', [id]);
    
    if (roles.length > 0) {
      const role = roles[0];
      
      // 检查权限：
      // 1. 如果是系统默认角色，任何人都可以访问
      // 2. 如果是用户自己的角色，需要用户已登录
      if (role.is_default || role.user_id === userId) {
        // 将下划线命名转换为驼峰命名
        const formattedRole = {
          id: role.id,
          name: role.name,
          description: role.description,
          avatar: role.avatar,
          prompt: role.prompt,
          greeting: role.greeting,
          isCustom: role.is_custom,
          isDefault: role.is_default,
          isAdult: role.is_adult,
          model: role.model,
          userId: role.user_id,
          createTime: role.create_time,
          updateTime: role.update_time,
          age: role.age,
          gender: role.gender,
          occupation: role.occupation,
          hobbies: role.hobbies,
          appearance: role.appearance,
          personality: role.personality,
          background: role.background,
          scenario: role.scenario,
          interactionPriorities: role.interaction_priorities,
          attentionPoints: role.attention_points
        };
        
        ctx.body = {
          errCode: 0,
          errMsg: '获取角色成功',
          data: formattedRole
        };
      } else {
        // 无权访问，返回null
        ctx.status = 403;
        ctx.body = {
          errCode: 'PERMISSION_DENIED',
          errMsg: '无权访问该角色',
          data: null
        };
      }
    } else {
      ctx.status = 404;
      ctx.body = {
        errCode: 'ROLE_NOT_FOUND',
        errMsg: '未找到该角色',
        data: null
      };
    }
  } catch (error) {
    console.error('获取角色失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'GET_ROLE_FAILED',
      errMsg: '获取角色失败：' + error.message,
      data: null
    };
  }
});

/**
 * 添加角色
 * POST /roles/addRole
 */
router.post('/addRole', async (ctx) => {
  const { role } = ctx.request.body;
  
  // 参数校验
  if (!role) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '角色信息不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 生成UUID
    const roleId = uuidv4();
    
    // 确保角色有必要的字段
    const completeRole = {
      id: roleId,
      ...ensureRoleFields(role, userId)
    };
    
    // 构建SQL插入语句
    const fields = Object.keys(completeRole).join(', ');
    const placeholders = Object.keys(completeRole).map(() => '?').join(', ');
    const values = Object.values(completeRole);
    
    // 执行插入
    const [result] = await pool.execute(
      `INSERT INTO roles (${fields}) VALUES (${placeholders})`,
      values
    );
    
    if (result.affectedRows > 0) {
      // 将下划线命名转换为驼峰命名
      const formattedRole = {
        ...Object.keys(completeRole).reduce((acc, key) => {
          // 将数据库字段名转换为API字段名（下划线转驼峰）
          const apiKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
          acc[apiKey] = completeRole[key];
          return acc;
        }, {})
      };
      
      ctx.body = {
        errCode: 0,
        errMsg: '添加角色成功',
        data: formattedRole
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        errCode: 'ADD_FAILED',
        errMsg: '添加角色失败',
        data: null
      };
    }
  } catch (error) {
    console.error('添加角色失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'ADD_ROLE_FAILED',
      errMsg: '添加角色失败：' + error.message,
      data: null
    };
  }
});

/**
 * 更新角色
 * POST /roles/updateRole
 */
router.post('/updateRole', async (ctx) => {
  const { role } = ctx.request.body;
  
  // 参数校验
  if (!role || !role.id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '角色信息或ID不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询角色，确认权限
    const [roles] = await pool.execute('SELECT * FROM roles WHERE id = ?', [role.id]);
    
    if (roles.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'ROLE_NOT_FOUND',
        errMsg: '未找到该角色',
        data: null
      };
      return;
    }
    
    const existingRole = roles[0];
    
    // 检查权限，只能更新用户自己的角色，不能更新系统默认角色
    if (existingRole.is_default || existingRole.user_id !== userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '无权更新该角色',
        data: null
      };
      return;
    }
    
    // 确保角色有必要的字段
    const completeRole = ensureRoleFields({ ...existingRole, ...role }, userId);
    
    // 移除不能更新的字段
    delete completeRole.id;
    delete completeRole.user_id;
    delete completeRole.is_default;
    delete completeRole.create_time;
    
    // 构建SQL更新语句
    const updateFields = Object.keys(completeRole).map(key => `${key} = ?`).join(', ');
    const values = [...Object.values(completeRole), role.id];
    
    // 执行更新
    const [result] = await pool.execute(
      `UPDATE roles SET ${updateFields} WHERE id = ?`,
      values
    );
    
    if (result.affectedRows > 0) {
      // 将下划线命名转换为驼峰命名
      const formattedRole = {
        id: role.id,
        ...Object.keys(completeRole).reduce((acc, key) => {
          // 将数据库字段名转换为API字段名（下划线转驼峰）
          const apiKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
          acc[apiKey] = completeRole[key];
          return acc;
        }, {})
      };
      
      ctx.body = {
        errCode: 0,
        errMsg: '更新角色成功',
        data: formattedRole
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        errCode: 'UPDATE_FAILED',
        errMsg: '更新角色失败',
        data: null
      };
    }
  } catch (error) {
    console.error('更新角色失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'UPDATE_ROLE_FAILED',
      errMsg: '更新角色失败：' + error.message,
      data: null
    };
  }
});

/**
 * 删除角色
 * POST /roles/deleteRole
 */
router.post('/deleteRole', async (ctx) => {
  const { id } = ctx.request.body;
  
  // 参数校验
  if (!id) {
    ctx.status = 400;
    ctx.body = {
      errCode: 'PARAM_IS_NULL',
      errMsg: '角色ID不能为空',
      data: null
    };
    return;
  }
  
  try {
    // 从中间件获取用户ID
    const userId = ctx.state.userId;
    
    // 查询角色，确认权限
    const [roles] = await pool.execute('SELECT * FROM roles WHERE id = ?', [id]);
    
    if (roles.length === 0) {
      ctx.status = 404;
      ctx.body = {
        errCode: 'ROLE_NOT_FOUND',
        errMsg: '未找到该角色',
        data: null
      };
      return;
    }
    
    const role = roles[0];
    
    // 检查权限，只能删除用户自己的角色，不能删除系统默认角色
    if (role.is_default || role.user_id !== userId) {
      ctx.status = 403;
      ctx.body = {
        errCode: 'PERMISSION_DENIED',
        errMsg: '无权删除该角色',
        data: null
      };
      return;
    }
    
    // 执行删除
    const [result] = await pool.execute('DELETE FROM roles WHERE id = ?', [id]);
    
    if (result.affectedRows > 0) {
      ctx.body = {
        errCode: 0,
        errMsg: '删除角色成功',
        data: {
          success: true
        }
      };
    } else {
      ctx.status = 500;
      ctx.body = {
        errCode: 'DELETE_FAILED',
        errMsg: '删除角色失败',
        data: null
      };
    }
  } catch (error) {
    console.error('删除角色失败', error);
    ctx.status = 500;
    ctx.body = {
      errCode: 'DELETE_ROLE_FAILED',
      errMsg: '删除角色失败：' + error.message,
      data: null
    };
  }
});

module.exports = router; 